package com.itheima.controller;


import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Tag;
import com.itheima.service.TagService;
import com.itheima.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping("/tag")
@RestController
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,RequestMethod.POST}, origins="*")
public class TagController {

    @Autowired
    private TagService tagService;
    @Autowired
    private IdWorker idWorker;

    /**
     * 2020年8月4日09:27:16
     * 添加标签
     * @param tag
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Tag tag){
        tag.setUid(DigestUtils.md5DigestAsHex((idWorker.nextId()+"").getBytes()));//利用雪花算法生成uid再进行加密
        tag.setCreateTime(new Date());
        tag.setUpdateTime(new Date());
        tagService.add(tag);
        return new Result("success","添加标签成功");
    }


    /**
     * 批量根据uid删除标签
     * @param tagList
     * @return
     */
    @PostMapping("/deleteBatch")
    public Result deleteByUids(@RequestBody List<Tag>tagList){
        for (Tag tag : tagList) {
            tagService.deleteByUid(tag.getUid());
        }
        return new Result("success","删除标签成功");
    }

    /**
     * 编辑标签
     * @param tag
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Tag tag){
        tag.setUpdateTime(new Date());
        tagService.edit(tag);
        return new Result("success","编辑标签成功");
    }

    /**
     * 分页查询
     * @param searchMap
     * @return
     */
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String,Object> searchMap){
        Page<Tag> tagPage=tagService.findPage(searchMap);
        PageResult<Tag> tagPageResult = new PageResult<>(tagPage.getTotal(), tagPage.getResult());
        com.itheima.entity.Page<Tag> objectPage = new com.itheima.entity.Page<>();
        objectPage.setRecords(tagPageResult.getRows());
        objectPage.setTotal(Integer.parseInt(tagPageResult.getTotal()+""));
        return new Result("success",objectPage);
    }

    /**
     * 置顶排序
     * @param tag
     * @return
     */
    @PostMapping("/stick")
    public Result stick(@RequestBody Tag tag){
        tagService.stick(tag);
        return new Result("success","置顶成功");
    }

    /**
     * 根据引用排序
     * @param
     * @return
     */
    @PostMapping("/tagSortByCite")
    public Result tagSortByCite(){
        tagService.tagSortByCite();
        return new Result("success","根据引用排序成功");
    }


    @PostMapping("/tagSortByClickCount")
    public Result tagSortByClickCount(){
        tagService.tagSortByClickCount();
        return new Result("success","根据点击排序成功");
    }

}
